import 'package:flutter/material.dart';

/// 路由配置参数
class RouteOptions {
  final Widget Function(dynamic args) page;
  RouteOptions({this.page});
}

/// Router构建组件
class RouterInit extends StatelessWidget {
  final Widget Function(Route<dynamic> Function(RouteSettings), GlobalKey<NavigatorState>) builder;

  /// 路由配置列表
  final Map<String, RouteOptions> routers;

  /// 空路由替代页面
  final RouteOptions unKnowRoute;

  const RouterInit({
    @required this.builder,
    @required this.routers,
    this.unKnowRoute,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Route<dynamic> Function(RouteSettings) onGenerateRoute = (settings) {
      return MaterialPageRoute(
        settings: settings,
        builder: (context) {
          final url = settings.name;
          final args = settings.arguments;

          if (routers.containsKey(url)) {
            return routers[url].page(args);
          }

          if (unKnowRoute != null) {
            return unKnowRoute.page(args);
          }

          return UnKnowPage();
        },
      );
    };
    return builder(onGenerateRoute, _routeKey);
  }
}

/// 找不到路由时的备用路由
class UnKnowPage extends StatelessWidget {
  const UnKnowPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('404'),
      ),
      body: Center(
        child: Text('你似乎进入了一个未知的世界'),
      ),
    );
  }
}

/// 路由key
GlobalKey<NavigatorState> _routeKey = GlobalKey();

/// 用于不使用ctx跳转路由
NavigatorState get router => _routeKey.currentState;